﻿using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using FingerTip.Sms.Aliyun.Helper;
using FingerTip.Sms.Aliyun.Internal;
using FingerTip.Sms.Core;
using FingerTip.Sms.Core.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace FingerTip.Sms.Aliyun
{
    public class AliyunSmsService : ISmsService
    {
        public Task<SendResult> SendCodeAsync(string phone, string code)
        {
            Guard.ArgumentNotNullOrEmpty(nameof(phone), phone);
            Guard.ArgumentNotNullOrEmpty(nameof(code), code);

            var client = new AliyunSmsClient();
            var acsClient = client.AcsClient;
            var request = new SendSmsRequest();
            var result = new SendResult();
            try
            {
                request.PhoneNumbers = phone;
                request.SignName = client.AliyunSmsSetting.SignName;
                request.TemplateCode = client.AliyunSmsSetting.TemplateCode;
                request.TemplateParam = string.Format(client.AliyunSmsSetting.TemplateParam, code);
                request.OutId = client.AliyunSmsSetting.OutId;

                var sendSmsResponse = acsClient.GetAcsResponse(request);
                if ("OK".Equals(sendSmsResponse.Code, StringComparison.CurrentCultureIgnoreCase))
                {
                    result.IsSuccess = true;
                }
                else
                {
                    result.IsSuccess = false;
                    result.ErrorMessage = sendSmsResponse.Message;
                }
            }
            catch (ClientException e)
            {
                AliyunSmsHelper.LoggerAction("Error", e.ToString());
                result.IsSuccess = false;
                result.ErrorMessage = e.ErrorMessage;
            }
            catch (Exception e)
            {
                AliyunSmsHelper.LoggerAction("Error", e.ToString());
                result.IsSuccess = false;
                result.ErrorMessage = e.Message;
            }
            return Task.FromResult(result);
        }

        public Task<SendResult> SendTemplateMessageAsync(SendTemplateMessageInput message) =>
            throw new NotImplementedException();
    }
}
